package com.dodock.banglapapers.server.helper;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class DDNNewsDetailBDProtidin {

	public String Generate(String newsid) throws IOException {
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		try {
			Entity detailsEntity = datastore.get(KeyFactory.createKey(
					"NewsDetails", "bd_protidin_" + newsid));
			Text text = (Text) detailsEntity.getProperty("data");
			String data = Settings.replaceExtras(text.getValue());
			System.out.println("RETRIVING FROM DATASTORE");
			return data;
		} catch (EntityNotFoundException e) {
			System.out.println("RETRIVING FROM WEB");
			Connection.Response response = Jsoup
					.connect(newsid)
					.userAgent(
							"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
					.timeout(30000).execute();

			Document doc = response.parse();
			JsonObject news = new JsonObject();
			news.addProperty("id", newsid);
			news.addProperty("sharelink", newsid);

			Element element = doc.select("div[id=newsDtl]").first();

			Elements imgElements = element.select("a");
			if (!imgElements.isEmpty()) {
				JsonArray imageArray = new JsonArray();
				String image = imgElements.first().attr("href").trim();
				JsonObject obj = new JsonObject();
				obj.addProperty("url", image);
				System.out.println("Image : " + image);
				imageArray.add(obj);
				news.add("gallery", imageArray);
			} else {
				System.out.println("No Image");
			}

			String details = "";
			details = element.text();

			if (details.length() > 0) {
				details = details.replaceAll("\u00a0", "<br/>");
				news.addProperty("details", details);
				System.out.println("Details : " + details);
				String data = news.toString();
				data = Settings.replaceExtras(data);
				Text text = new Text(data);
				Entity detailsEntity = new Entity("NewsDetails", "bd_protidin_"
						+ newsid);
				detailsEntity.setProperty("data", text);
				datastore.put(detailsEntity);
				return data;
			} else {
				return "{}";
			}
		}
	}
}
